package com.example.signsystem.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.signsystem.entity.parm.BlogInfoParam;
import com.example.signsystem.entity.po.BlogPO;
import com.example.signsystem.entity.po.StudentsPO;
import com.example.signsystem.mapper.BlogMapper;
import com.example.signsystem.mapper.StudentsMapper;
import com.example.signsystem.service.IBlogService;
import com.qcby.framework.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

@Slf4j
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, BlogPO> implements IBlogService {

    @Resource
    private StudentsMapper studentsMapper;

    @Override
    public Boolean blogInfoChange(BlogInfoParam blogInfoParam) {
        /**判断有没有这个学生的博客信息，没有则添加，有则更新**/
        StudentsPO studentsPO = studentsMapper.selectOne(new LambdaQueryWrapper<StudentsPO>()
                .eq(StudentsPO::getName, blogInfoParam.getName()));
        if (ObjectUtil.isNull(studentsPO)) {
            throw new ServiceException("500", "暂无学生信息，请先注册");
        }
        Long userId = studentsPO.getId();
        String now = DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN);
        BlogPO blogPO = this.baseMapper.selectOne(new LambdaQueryWrapper<BlogPO>().eq(BlogPO::getUserId, userId)
                .eq(BlogPO::getLatestTime,now));
        if (ObjectUtil.isNull(blogPO)) {
            blogPO = BeanUtil.copyProperties(blogInfoParam, BlogPO.class);
            blogPO.setUserId(userId);
            blogPO.setLatestTime(now);
            /**学生表博客数量维护**/
            studentsBlogCount(userId,blogPO.getBlogCount());
            return this.baseMapper.insert(blogPO) > 0;
        }
        blogPO.setBlogCount(blogInfoParam.getBlogCount());
        /**学生表博客数量维护**/
        studentsBlogCount(userId,blogInfoParam.getBlogCount());
        return this.baseMapper.updateById(blogPO) > 0;
    }

    /**
     * 学生表博客数量维护
     */
    public void studentsBlogCount(Long userId,Integer blogCount){
        LambdaUpdateWrapper<StudentsPO> updateWrapper=new LambdaUpdateWrapper<StudentsPO>()
                .set(StudentsPO::getBlogCount,blogCount)
                .eq(StudentsPO::getId,userId);
        studentsMapper.update(null,updateWrapper);
    }


}
